package cn.jiedh.app.meiweidk.Utils.tool;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.text.TextUtils;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import cn.jiedh.app.meiweidk.Utils.config.ConfigUtils;
import cn.jiedh.app.meiweidk.Utils.event.Constant;
import cn.jiedh.app.meiweidk.Utils.event.EventScreen;
import cn.jiedh.app.meiweidk.Utils.event.EventUtils;
import cn.jiedh.app.meiweidk.app.MyApp;
import cn.jiedh.app.meiweidk.buried.BuriedBean;
import cn.jiedh.app.meiweidk.buried.BuriedIntentService;
import cn.jiedh.app.meiweidk.entity.ApplicationInfoBean;
import cn.jiedh.app.meiweidk.mine.PersonInfo;
import cn.jiedh.app.meiweidk.welcome.AdverBean;
import cn.jiedh.app.meiweidk.welcome.MoneyAndYTData;
import cn.jiedh.app.meiweidk.welcome.MoneyBean;
import cn.jiedh.app.meiweidk.welcome.YongTuBean;
import cn.jpush.android.api.JPushInterface;


public class SPUtils {
    /**
     * 保存在手机里面的文件名
     */
    public static final String APP_COMMON_FILE_NAME = "houhanshare";
    private static SharedPreferences mSp;
    private static final String LAST_VERSION = "last_version";//最近一个版本号 用于显示引导页条件的判断
    private static Context mContext;
    private static DbManager db;

    public static void initSPUtil(Context context) {
        mContext = context;
        db = x.getDb(MyApp.getInstance().getDaoConfig());
    }

    public static SharedPreferences initSharedPreferences(Context cxt) {
        if (mSp == null) {
            mSp = cxt.getSharedPreferences(APP_COMMON_FILE_NAME,
                Context.MODE_PRIVATE);
        }
        return mSp;
    }

    /**
     * 保存用户登录数据
     *
     * @param phone 用户登录的手机号
     * @param token 后端返回的token
     * @return 是否保存成功
     */
    public static boolean saveUser(String phone, String token) {
        SharedPreferences prefs = initSharedPreferences(mContext);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(ConfigUtils.INFO_LOGIN, phone);
        editor.putString(ConfigUtils.REQ_TOKEN, token);
        return editor.commit();
    }

    /**
     * 清空用户登录数据
     *
     * @return 是否清除成功
     */
    public static boolean clearUser(Context activity) {
        SharedPreferences prefs = initSharedPreferences(mContext);
        SharedPreferences.Editor editor = prefs.edit();
        String mobilePhone = getPhone();
        editor.remove(ConfigUtils.INFO_LOGIN);
        editor.remove(ConfigUtils.REQ_TOKEN);
        editor.remove(ConfigUtils.USER_NAME);
        editor.remove(ConfigUtils.USER_CITY);
        editor.remove(ConfigUtils.USER_IDCARD);
        Intent intent = new Intent(activity, BuriedIntentService.class);
        intent.putExtra("mobilePhone", mobilePhone);
        activity.startService(intent);
        JPushInterface.setAlias(MyApp.mContext, "", null);
        EventScreen eventScreen = new EventScreen(Constant.LOGINOUT, "");
        EventUtils.getDefault().forward(eventScreen);
        return editor.commit();
    }


    /**
     * 保存信息时保存绿色通道用户信息
     *
     * @param info
     * @return
     */
    public static boolean saveUserData(PersonInfo info) {
        SharedPreferences prefs = initSharedPreferences(mContext);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(ConfigUtils.USER_NAME, info.getUsername());
        editor.putString(ConfigUtils.USER_CITY, info.getCityLive());
        editor.putString(ConfigUtils.USER_IDCARD, info.getIdCard());

        return editor.commit();
    }


    /**
     * 清空数据
     */
    public static boolean clearPerfssences() {

        SharedPreferences prefs = initSharedPreferences(mContext);
        SharedPreferences.Editor edit = prefs.edit();
        edit.clear();
        return edit.commit();
    }


    /**
     * 保存数据的方法，我们需要拿到保存数据的具体类型，然后根据类型调用不同的保存方法
     *
     * @param key
     * @param object
     */
    public static boolean saveToApp(Context context, String key, Object object) {
        SharedPreferences sp = context.getApplicationContext()
            .getSharedPreferences(APP_COMMON_FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        if (object == null) {
            return false;
        }
        if (object instanceof String) {
            editor.putString(key, (String) object);
        } else if (object instanceof Integer) {
            editor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean) {
            editor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float) {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long) {
            editor.putLong(key, (Long) object);
        } else if (object instanceof Set) {
            editor.putStringSet(key, (Set<String>) object);
        } else {
            editor.putString(key, object.toString());
        }
        return editor.commit();
    }

    /**
     * 得到保存数据的方法，我们根据默认值得到保存的数据的具体类型，然后调用相对于的方法获取值
     *
     * @param key
     * @param defaultObject
     * @return
     */
    public static Object getFromApp(Context context, String key, Object defaultObject) {
        SharedPreferences sp = context.getApplicationContext()
            .getSharedPreferences(APP_COMMON_FILE_NAME,
                Context.MODE_PRIVATE);
        if (defaultObject instanceof String) {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        } else if (defaultObject instanceof Set) {
            return sp.getStringSet(key, ((Set<String>) defaultObject));
        }
        return null;
    }

    public static String getValue(String key) {
        SharedPreferences sp = x.app().getApplicationContext()
            .getSharedPreferences(APP_COMMON_FILE_NAME,
                Context.MODE_PRIVATE);

        return sp.getString(key, "");
    }

    /**
     * 序列化对象
     *
     * @return
     * @throws IOException
     */
    public static String serialize(Object object) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(object);
        String serStr = byteArrayOutputStream.toString("ISO-8859-1");
        serStr = java.net.URLEncoder.encode(serStr, "UTF-8");
        objectOutputStream.close();
        byteArrayOutputStream.close();
        return serStr;
    }

    /**
     * 反序列化对象
     *
     * @param str
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static Object deSerialization(String str) throws IOException, ClassNotFoundException {
        String redStr = java.net.URLDecoder.decode(str, "UTF-8");
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(redStr.getBytes("ISO-8859-1"));
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        Object object = (Object) objectInputStream.readObject();
        objectInputStream.close();
        byteArrayInputStream.close();
        return object;
    }


    /**
     * 保存广告对象
     *
     * @param
     * @return
     */
    public static boolean putAdver(AdverBean adverBean) {
        String str = JsonUtil.objectToJson(adverBean);
        return saveToApp(MyApp.mContext, ConfigUtils.ADVER, str);
    }

    /**
     * 提取广告
     *
     * @return
     */
    public static AdverBean getadver() {
        AdverBean adverBean = null;
        String str = (String) getFromApp(MyApp.mContext, ConfigUtils.ADVER, "");
        try{
            adverBean= JsonUtil.jsonToObject(str,AdverBean.class);
        }catch (Exception e){

        }
        return adverBean;
    }

    /**
     * 保存到手机的token
     *
     * @return
     */
    public static String getToken(Context context) {
        String token = (String) getFromApp(context.getApplicationContext(), ConfigUtils.REQ_TOKEN, "");
        if (TextUtils.isEmpty(token)) {
            return "";
        }
        return token;
    }

    /**
     * 保存到手机的cookie
     *
     * @return
     */
    public static String getCookie(Context context) {
        String cookie = (String) getFromApp(context.getApplicationContext(), ConfigUtils.REQ_COOKIE, "");
        if (TextUtils.isEmpty(cookie)) {
            return "";
        }
        return cookie;
    }

    /**
     * 保存到手机的登录状态
     *
     * @return
     */
    public static boolean getIsLogin() {
        String isLogin = (String) getFromApp(mContext, ConfigUtils.INFO_LOGIN, "");
        if (TextUtils.isEmpty(isLogin)) {
            return false;
        }
        return true;
    }

    /**
     * 获取登录用户手机号
     *
     * @return 用户登录的手机号
     */
    public static String getPhone() {
        String phone = (String) getFromApp(mContext.getApplicationContext(), ConfigUtils.INFO_LOGIN, "");
        if (TextUtils.isEmpty(phone)) {
            return "";
        }
        return phone;
    }


    /**
     * 获取cookies
     *
     * @return
     */
    public static String getHeadLogo(Context context) {
        String cookie = (String) getFromApp(context.getApplicationContext(), ConfigUtils.REQ_COOKIE, "");
        if (TextUtils.isEmpty(cookie)) {
            return "";
        }
        return cookie;
    }

    /**
     * 移除某个key值已经对应的值
     *
     * @param key
     */
    public static void remove(Context context, String key) {
        try {
            SharedPreferences sp = context.getApplicationContext().getSharedPreferences(
                APP_COMMON_FILE_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.remove(key);
            editor.commit();
        } catch (Exception e) {
        }
    }

    public static String getLastVersion(Context cxt) {
        SharedPreferences prefs = initSharedPreferences(cxt);
        return prefs.getString(LAST_VERSION, null);
    }

    public static void setLastVersion(Context cxt, String version) {
        SharedPreferences prefs = initSharedPreferences(cxt);
        SharedPreferencesCompat.apply(prefs.edit().putString(LAST_VERSION, version));
    }

//    /**
//     * 保存埋点数据
//     *
//     * @param list     需要保存的埋点数据
//     * @return 是否保存成功
//     */
//    public static boolean saveBuriedList(List<BuriedBean> list) {
//
//        List<BuriedBean> oldList = getBuriedList();
//        oldList.addAll(list);
//        SharedPreferences prefs = initSharedPreferences(mContext);
//        SharedPreferences.Editor editor = prefs.edit();
//        if (oldList == null || oldList.size() <= 0) {
//            return false;
//        }
//        Gson gson = new Gson();
//        String buriedStr = gson.toJson(oldList);
//        return editor.putString("buried", buriedStr).commit();
//    }

    /**
     * 保存埋点数据
     *
     * @param list
     */
    public static void saveBuriedList(List<BuriedBean> list) {
        try {
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    db.saveBindingId(list.get(i));
                    L.i("deletelist", getBuriedList().toString());
                }
            }
        } catch (DbException e) {

        }
    }

    public static void saveBuried(BuriedBean bean) {
        try {
            if (bean != null) {
                db.saveBindingId(bean);
                L.i("deletelist", getBuriedList().toString());
            }

        } catch (DbException e) {

        }
    }

    public static void saveBuried(String action, String targetType, String targetName, String verifyCode,
                                  String currentPage, String loanMoney, String loanType, String targetId) {
        BuriedBean bean = new BuriedBean();
        bean.setAction(action);
        bean.setTargetType(targetType);
        bean.setTargetName(targetName);
        bean.setVerifyCode(verifyCode);
        bean.setCurrentPage(currentPage);
        bean.setLoanMoney(loanMoney);
        bean.setLoanType(loanType);
        bean.setTargetId(targetId);
        saveBuried(bean);
    }

    /**
     * 获取埋点数据
     */
    public static List<BuriedBean> getBuriedList() {
        Cursor cursor = null;
        List<BuriedBean> list = null;
        try {
            list = db.findAll(BuriedBean.class);
            if (list == null) {
                list = new ArrayList<>();
            }
        } catch (DbException e) {
            e.printStackTrace();
            if (list == null) {
                list = new ArrayList<>();
            }
        }
//        try {
//            cursor = db.execQuery("SELECT * FROM BuriedBean");
//            while (cursor != null && cursor.moveToNext()) {
////               list = db.findAll(BuriedBean.class);
//                BuriedBean s = new BuriedBean();
//                s.setAction(cursor.getString(cursor.getColumnIndex("action")));
//                s.setActName(cursor.getString(cursor.getColumnIndex("actName")));
//                s.setActTime(cursor.getString(cursor.getColumnIndex("actTime")));
//                s.setCurrentPage(cursor.getString(cursor.getColumnIndex("currentPage")));
//                s.setInterestRate(cursor.getString(cursor.getColumnIndex("interestRate")));
//                s.setInviteChannel(cursor.getString(cursor.getColumnIndex("inviteChannel")));
//                s.setIsLogin(cursor.getString(cursor.getColumnIndex("isLogin")));
//                s.setIsReact(cursor.getString(cursor.getColumnIndex("isReact")));
//                s.setLoanMoney(cursor.getString(cursor.getColumnIndex("loanMoney")));
//                s.setLoanSort(cursor.getString(cursor.getColumnIndex("loanSort")));
//                s.setLoanTerm(cursor.getString(cursor.getColumnIndex("loanTerm")));
//                s.setLoanType(cursor.getString(cursor.getColumnIndex("loanType")));
//                s.setQueryCondition(cursor.getString(cursor.getColumnIndex("queryCondition")));
//                s.setShareChannel(cursor.getString(cursor.getColumnIndex("shareChannel")));
//                s.setStayTime(cursor.getString(cursor.getColumnIndex("stayTime")));
//                s.setTargetId(cursor.getString(cursor.getColumnIndex("targetId")));
//                s.setTargetName(cursor.getString(cursor.getColumnIndex("targetName")));
//                s.setTargetType(cursor.getString(cursor.getColumnIndex("targetType")));
//                s.setVerifyCode(cursor.getString(cursor.getColumnIndex("verifyCode")));
//                list.add(s);
//            }
//            if (cursor != null) {
//                cursor.close();
//                cursor = null;
//            }
//        } catch (DbException e) {
//            e.printStackTrace();
//        }

        if (list == null) {
            list = new ArrayList<>();
        }
        return list;
    }

    /**
     * 删除数据表
     */
    public static void deleteBuriedList() {
        try {
            db.delete(BuriedBean.class);
            L.i("deletelist", "------");
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

//    /**
//     * 获取埋点数据
//     *
//     * @return 是否成功返回埋点数据
//     */
//    public static List<BuriedBean> getBuriedList() {
//        List<BuriedBean> list;
//        Gson gson = new Gson();
//        SharedPreferences prefs = initSharedPreferences(mContext);
//        String buriedStr = prefs.getString("buried", "");
//        if (TextUtils.isEmpty(buriedStr)) {
//            return new ArrayList<>();
//        } else {
//            list = gson.fromJson(buriedStr, new TypeToken<List<BuriedBean>>() {
//            }.getType());
//            if (list.size() <= 0) {
//                return new ArrayList<>();
//            }
//        }
//        return list;
//    }

    /**
     * 清除埋点数据
     *
     * @return 返回是否清除数据成功
     */
    public static boolean clearBuried() {
        SharedPreferences prefs = initSharedPreferences(mContext);
        SharedPreferences.Editor editor = prefs.edit();
        editor.remove("buried");
        return editor.commit();
    }

    /**
     * 获取上次请求应用基本信息的时间
     *
     * @return
     */
    public static String getTime() {
        String time = (String) getFromApp(mContext, ConfigUtils.SHOW_TIME, "");
        if (TextUtils.isEmpty(time)) {
            return "";
        }
        return time;
    }

    /**
     * 获取应用基本信息
     *
     * @return
     */
    public static ApplicationInfoBean getAppInfoFromSP() {
        ApplicationInfoBean applicationInfoBean = new ApplicationInfoBean();
        applicationInfoBean.setShareLink((String) SPUtils.getFromApp(mContext, "application_shareLink", ""));
        applicationInfoBean.setShareImgUrl((String) SPUtils.getFromApp(mContext, "application_shareImgUrl", ""));
        applicationInfoBean.setShareTitle((String) SPUtils.getFromApp(mContext, "application_shareTitle", ""));
        applicationInfoBean.setShareContent((String) SPUtils.getFromApp(mContext, "application_shareContent", ""));
        applicationInfoBean.setAboutUsUrl((String) SPUtils.getFromApp(mContext, "application_aboutUsUrl", ""));
        applicationInfoBean.setCustomerServicePhone((String) SPUtils.getFromApp(mContext, "application_customerServicePhone", ""));
        applicationInfoBean.setWorkTime((String) SPUtils.getFromApp(mContext, "application_workTime", ""));
        applicationInfoBean.setAgreementUrl((String) SPUtils.getFromApp(mContext, "application_agreementUrl", ""));
        applicationInfoBean.setBombBoxNum((int) SPUtils.getFromApp(mContext, "application_bombBoxNum", 0));
        applicationInfoBean.setQuestionnaireTime((int) SPUtils.getFromApp(mContext, "application_questionnaireTime", 30));
        applicationInfoBean.setQuestionnaireNum((int) SPUtils.getFromApp(mContext, "application_questionnaireNum", 30));
        return applicationInfoBean;
    }

    /**
     * 保存应用基本信息
     *
     * @param applicationInfoBean
     */
    public static void saveAppInfoToSP(ApplicationInfoBean applicationInfoBean) {
        if (applicationInfoBean != null) {
            SPUtils.saveToApp(mContext, "application_shareLink", applicationInfoBean.getShareLink());
            SPUtils.saveToApp(mContext, "application_shareImgUrl", applicationInfoBean.getShareImgUrl());
            SPUtils.saveToApp(mContext, "application_shareTitle", applicationInfoBean.getShareTitle());
            SPUtils.saveToApp(mContext, "application_shareContent", applicationInfoBean.getShareContent());
            SPUtils.saveToApp(mContext, "application_aboutUsUrl", applicationInfoBean.getAboutUsUrl());
            SPUtils.saveToApp(mContext, "application_customerServicePhone", applicationInfoBean.getCustomerServicePhone());
            SPUtils.saveToApp(mContext, "application_workTime", applicationInfoBean.getWorkTime());
            SPUtils.saveToApp(mContext, "application_agreementUrl", applicationInfoBean.getAgreementUrl());
            SPUtils.saveToApp(mContext, "application_bombBoxNum", applicationInfoBean.getBombBoxNum());
            SPUtils.saveToApp(mContext, "application_questionnaireTime", applicationInfoBean.getQuestionnaireTime());
            SPUtils.saveToApp(mContext, "application_questionnaireNum", applicationInfoBean.getQuestionnaireNum());
            SPUtils.saveToApp(mContext, "dialogNum", applicationInfoBean.getBombBoxNum());
        }
    }

    /**
     * 判断是否第一次进入消息页面
     * 用于数据库的第一次保存判断
     *
     * @return 0, 不是第一次，1，是第一次
     */
    public static Boolean getIntoMessageListState() {
        Boolean state = (Boolean) getFromApp(mContext, ConfigUtils.INFO_MESSAGE, true);
        return state;
    }

    /**
     * 设置消息页面为非第一次进入
     */
    public static void setIntoMessageListState() {
        saveToApp(mContext, ConfigUtils.INFO_MESSAGE, false);
    }

    /**
     * 获取H5回来的page参数
     *
     * @return
     */
    public static String h52appgetpage() {
        String page = (String) getFromApp(mContext, ConfigUtils.PAGE, "");
        if (TextUtils.isEmpty(page)) {
            return "";
        }
        return page;
    }

    public static boolean clearH5() {
        SharedPreferences prefs = initSharedPreferences(mContext);
        SharedPreferences.Editor editor = prefs.edit();
        editor.remove(ConfigUtils.PAGE);
        editor.remove(ConfigUtils.PID);
        editor.remove(ConfigUtils.RID);
        return editor.commit();
    }

    public static String getpid() {
        String pid = (String) getFromApp(mContext, ConfigUtils.PID, "");
        if (TextUtils.isEmpty(pid)) {
            return "";
        }
        return pid;
    }

    public static String getrid() {
        String rid = (String) getFromApp(mContext, ConfigUtils.RID, "");
        if (TextUtils.isEmpty(rid)) {
            return "";
        }
        return rid;
    }

    public static String getmoney() {
        String money = (String) getFromApp(mContext, ConfigUtils.MONEY, "5000");
        return money;
    }

    public static String getType() {
        String type = (String) getFromApp(mContext, ConfigUtils.TYPE, "购物");
        return type;
    }

    public static boolean clearmoney() {
        SharedPreferences prefs = initSharedPreferences(mContext);
        SharedPreferences.Editor editor = prefs.edit();
        editor.remove(ConfigUtils.MONEY);
        return editor.commit();
    }

    /**
     * 保存金额和用途
     *
     * @param
     * @return
     */
    public static boolean putMoneyandYongtu(MoneyAndYTData moneyAndYTDatas) {
        String str = "";
        try {
            str = serialize(moneyAndYTDatas);
            saveToApp(MyApp.mContext, ConfigUtils.MONEYANYONGTU, "moneyandyongtu");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return saveToApp(MyApp.mContext, ConfigUtils.MONEYANYONGTU, str);
    }

    /**
     * 提取金额数组
     *
     * @return
     */
    public static List<MoneyBean> getmoneylist() {
        MoneyAndYTData moneyAndYTData = null;
        String str = (String) getFromApp(MyApp.mContext, ConfigUtils.MONEYANYONGTU, "");
        try {
            moneyAndYTData = (MoneyAndYTData) deSerialization(str);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (moneyAndYTData == null) {
            moneyAndYTData = new MoneyAndYTData(new ArrayList<MoneyBean>(), new ArrayList<YongTuBean>());
        }
        return moneyAndYTData.getLoanAmount();
    }

    /**
     * 提取金额数组
     *
     * @return
     */
    public static List<YongTuBean> getyongtulist() {
        MoneyAndYTData moneyAndYTData = null;
        String str = (String) getFromApp(MyApp.mContext, ConfigUtils.MONEYANYONGTU, "");
        try {
            moneyAndYTData = (MoneyAndYTData) deSerialization(str);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (moneyAndYTData == null) {
            moneyAndYTData = new MoneyAndYTData(new ArrayList<MoneyBean>(), new ArrayList<YongTuBean>());
        }
        return moneyAndYTData.getLoanUsed();
    }

    public static String getMoney() {
        String money = (String) getFromApp(mContext, SPUtils.getPhone(), "10000");
        return money;
    }


}
